package cn.suchan.jianzhi.q3_link;

import java.util.ArrayList;
import java.util.Stack;

/**
 * 知识点：链表
 * 题目描述
 * 输入一个链表，按链表值从尾到头的顺序返回一个ArrayList。
 *
 * @author suchan
 * @date 2019/05/23
 */
public class Solution {

    /**
     * 借助中间List
     *
     * @param listNode
     * @return
     */
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> tempList = new ArrayList();
        ArrayList<Integer> resultList = new ArrayList();
        ListNode tempNode = listNode;

        while (tempNode != null) {
            tempList.add(tempNode.val);
            tempNode = tempNode.next;
        }

        for (int i = tempList.size() - 1; i >= 0; i--) {
            resultList.add(tempList.get(i));
        }
        return resultList;
    }

    /**
     * 借助Stack
     *
     * @param listNode
     * @return
     */
    public ArrayList<Integer> printListFromTailToHead1(ListNode listNode) {
        Stack<Integer> stack = new Stack<>();
        while (listNode != null) {
            stack.push(listNode.val);
            listNode = listNode.next;
        }

        ArrayList<Integer> list = new ArrayList<>();
        while (!stack.empty()) {
            list.add(stack.pop());
        }
        return list;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode listNode = new ListNode(67);
        ListNode listNode1 = new ListNode(0);
        ListNode listNode2 = new ListNode(24);
        ListNode listNode3 = new ListNode(56);
        listNode.next = listNode1;
        listNode1.next = listNode2;
        listNode2.next = listNode3;

        System.out.println("result==>" + solution.printListFromTailToHead(listNode));
        System.out.println("result==>" + solution.printListFromTailToHead1(listNode));
    }
}
